# -*- coding: utf-8 -*-#

# -------------------------------------------------------------------------------
# @Time:       2023/2/1 9:58
# Author:      Administrator
# @File:       http_helper.py
"""
请求时网络延迟较长.time_diff 由file_util.py 接入
"""
# -------------------------------------------------------------------------------

import datetime
import functools
import time
import urllib
from urllib.parse import urlparse
import json
import os
import ssl
import urllib3

# from url_media.file_util import time_diff

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)  # 禁用严重的警告信息，否则报
from urllib.request import urlopen
import bs4
from bs4 import BeautifulSoup


def get_static_url_content(url, encoding='utf-8', timeout=3600):
    '''
    获取静态网页内容 BeautifulSoup
    :param url:         网页url
    :param encoding:    网页编码
    :param timeout:     设置超时
    :return:
    '''
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'}
    req = request.Request(url, headers=headers)
    # html = urlopen(req, timeout=timeout)
    res = requests.request(method="GET", url=url, headers=headers)
    bsObj = BeautifulSoup(res.content, "html.parser", from_encoding=encoding)  # #lxml
    return bsObj

def time_diff(timestamp, _format='')->str:
    '''
    网络访问耗时 [结束时间-起始时间]
    Args:
        timestamp: 起始时间
        _format: 时H分M秒S

    Returns:
        time: 时间 str
    '''
    onlineTime = datetime.datetime.fromtimestamp(timestamp)
    localTime = datetime.datetime.now()
    result = localTime - onlineTime
    hours = int(result.seconds / 3600)
    minutes = int(result.seconds % 3600 / 60)
    seconds = result.seconds % 3600 % 60
    haoseconds = int(result.microseconds / 1000)

    # print("当前网络时间：{0}".format(localTime))
    # print("上次在线时间：{0}".format(onlineTime))
    # print("{0}天{1}时{2}分{3}秒{4}毫秒前在线".format(result.days, hours, minutes, seconds, haoseconds))
    if _format == 'H':
        return '{1}时{2}分{3}秒{4}毫秒'.format(result.days, hours, minutes, seconds, haoseconds)
    elif _format == 'M':
        return '{2}分{3}秒{4}毫秒'.format(result.days, hours, minutes, seconds, haoseconds)
    elif _format == 'S':
        return '{3}秒{4}毫秒'.format(result.days, hours, minutes, seconds, haoseconds)
    else:
        # return '{0}天{1}时{2}分{3}秒{4}毫秒'.format(result.days, hours, minutes, seconds, haoseconds)
        # 含微秒的日期时间，来源 比特量化
        dt_ms = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
        print(dt_ms)
        return dt_ms

def print_hi(str_json):
    # case1 如何将其中的\xa0去掉
    # move = dict.fromkeys((ord(c) for c in u"\xa0\n\t"))
    # output = name.translate(move)
    # print(output)

    # # case2
    # out = "".join(name.split())
    # print(out)
    # Use a breakpoint in the code line below to debug your script.
    # name= json.dumps(str_json, cls=NpEncoder, indent=4)
    reps = json.dumps(str_json, indent=2, ensure_ascii=False)
    print(reps)  # Press Ctrl+F8 to toggle the breakpoint.


def time_consume(info="used"):
    '''
    clock 用time.perf_counter()替换
    :param info:
    :return:
    '''

    # def _wrapper(*args, **kwargs):
    #     start = time.clock()
    #     fn(*args, **kwargs)
    #     print("%s cost %s second" % (fn.__name__, time.clock() - start))
    # return _wrapper

    def _time_me(fn):
        @functools.wraps(fn)
        def _wrapper(*args, **kwargs):
            start = time.perf_counter()
            fn(*args, **kwargs)
            print("%s %s %s" % (fn.__name__, info, time.perf_counter() - start), "second")

        return _wrapper

    return _time_me


class MyClass:
    i = 12345
    raw = {}
    url = ''

    ''' host,url,data'''

    def __init__(self, arg0, arg1, arg2):
        self.raw = arg1

        hh = urllib.parse.urlparse(arg0)
        if hh.netloc.find(':') == -1:
            self.url = arg0 + arg2

        else:
            self.url = arg0 + arg2

    def ctor(self, rw, ul):
        self.raw = rw
        self.url = ul

    def req(self):
        return 'hello world'


class NpEncoder(json.JSONEncoder):
    """
    默认的编码函数很多数据类型都不能编码
    Supports the following objects and types by default:

    +-------------------+---------------+
    | Python            | JSON          |
    +===================+===============+
    | dict              | object        |
    +-------------------+---------------+
    | list, tuple       | array         |
    +-------------------+---------------+
    | str               | string        |
    +-------------------+---------------+
    | int, float        | number        |
    +-------------------+---------------+
    | True              | true          |
    +-------------------+---------------+
    | False             | false         |
    +-------------------+---------------+
    | None              | null          |
    +-------------------+---------------+

    """

    def default(self, obj):
        # print(type(obj))
        if isinstance(obj, int):  # np.integer
            return int(obj)
        elif isinstance(obj, float):  # np.floating
            return float(obj)
        elif isinstance(obj, bytes):
            return str(obj, encodings='utf-8')
        # elif isinstance(obj, array):
        #    return obj.tolist()
        elif isinstance(obj, list):  # np.ndarray
            return obj.tolist()
        elif isinstance(obj, datetime.time) or isinstance(obj, datetime.date):
            return obj.strftime("%Y-%m-%d %H:%M:%S")
        else:
            return super(NpEncoder, self).default(obj)

        # json.dumps(data,cls=NpEncoder,indent=4)


import ssl
from urllib.parse import urlparse
from urllib import request
from urllib.parse import quote, unquote
import requests


class HttpHelp(object):

    @classmethod
    def jsonDataToUrlParams(self, params_data):
        ''' 将Json对象转化成Url字符串'''
        url_str = ''  # '?'
        nums = 0
        max_nums = len(params_data)
        for key in params_data:
            nums = nums + 1
            # 如果是最后一位就不要带上&
            # 拼为url字符串
            if nums == max_nums:
                url_str += str(key) + '=' + str(params_data[key])
            else:
                url_str += str(key) + '=' + str(params_data[key]) + '&'
        return url_str

    @classmethod
    def base64ToFile(self, file_name, b64, exists=True):
        ''' 将b64 写入文件'''

        import base64
        file_path = os.getcwd() + file_name
        print('dd : {}'.format(file_path))
        if exists and os.path.exists(file_path):
            os.remove(file_path)

        imgdata = base64.b64decode(b64)
        file = open(file_path, 'wb')
        file.write(imgdata)
        file.close()

    def down_file(self, url, filename):

        '''
        直接文件下载==get请求
        :param filename:文件名
        :return: 文件路径
        '''

        print(url + ' -- ')
        fake_useragent = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36',
            'Content-Type': 'application/pdf',
            'Host': 'liangjiang.oss-cn-beijing.aliyuncs.com',
            'Accept-Encoding': 'gzip,deflate',
            "Accept": 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9'
        }

        _url = urlparse(url)
        _p = unquote(_url.query)
        req = requests.get(url=url)  # stream=True,, headers = fake_useragent

        # 打印http请求信息
        print(req.request.headers)
        print(req.request.body)

        _fname = _url.path.rsplit('/')[-1]
        print(req.status_code)
        # 判断文件是否存在
        if req.status_code == 200:
            self.save_file(req, filename + os.sep + _fname)
        return filename + os.sep + _fname

    @classmethod
    def save_file(self, res, filename):
        '''
        请求网络地址，保存下载的文件
        '''

        if res.status_code != 200:
            print('http status_code ={}'.format(res.status_code))
            return
        # req.raise_for_status()  # 确保程序在下载失败时停止
        '''
        要求：调用时，判断 req.status_code == 200
        从Internet上下载文件和网页

        下载并保存到文件的步骤：
        ①调用requests.get()下载该文件
        ②用’wb’调用open()，以写二进制的方式打开一个新文件
        ③利用Respose对象的iter_content()方法循环
        ④在每次迭代中调用write()，将内容写入该文件
        ⑤调用close()关闭该文件
        ————————————————

        :param req:
        :param filename:
        :return:
        '''
        # 判断文件是否存在
        path = os.path.dirname(os.getcwd()) + os.sep + filename
        path = os.getcwd() + os.sep + filename

        abc = os.path.split(path)

        # 文件夹是否存在
        if not os.path.exists(abc[0]):
            os.makedirs(abc[0])

        # 如果文件已存在，则删除
        if os.path.exists(path) and os.path.isfile(path) == True:
            os.remove(path)

        with open(path, 'wb') as f:
            for chunk in res.iter_content(chunk_size=1024):
                f.write(chunk)

    def hum_convert(self, value):
        '''字节自适应转化单位KB、MB、GB'''
        units = ["B", "KB", "MB", "GB", "TB", "PB"]
        size = 1024.0
        for i in range(len(units)):
            if (value / size) < 1:
                return "%.2f%s" % (value, units[i])
            value = value / size


class time_consuming_request(object):
    '''
        requests 请求
    '''
    from urllib import request
    p_url = ''
    p_raw = {}

    # host = 'http://192.168.2.66:8082'
    host = 'https://api.woserve.com'  # 线上地址。不需要添加/api/
    host = 'https://api.wopaas.net'
    host = 'http://www.wopaas.net'
    host = 'http://localhost:44355'

    def __init__(self, _url=None):
        if _url and _url.startswith('http'):
            res = urlparse(_url)
            _host = res.netloc
            if _host != '' and res.scheme != '':
                self.host = '{}://{}'.format(res.scheme, _host)
        else:
            self.p_url = _url
        pass

    def setUrl(self, _url):
        self.p_url = _url

    def setHost(self, ht=None):
        ''' 指定Host url'''
        try:
            if ht != None and len(ht) > 0:
                self.host = ht
            else:
                res = urlparse(self.p_url)
                _host = res.netloc
                if _host != '' and res.scheme != '':
                    self.host = '{}://{}'.format(res.scheme, _host)
                return

        except Exception as ex:
            print(ex)
            # continue

    # def setHostApi(self, ht=HttpApi.DEFAULT):
    #     ''' 枚举方式指定Host'''
    #     if ht != HttpApi.DEFAULT:
    #         self.host = self.hosts[ht]
    #     else:
    #         self.host = self.hosts[HttpApi.Local]

    def consume_time(self, func):
        ''' 耗时'''
        import datetime
        import time

        t1 = datetime.datetime.now().microsecond
        t3 = time.mktime(datetime.datetime.now().timetuple())  # **datetime转时间戳**
        # 这里调用你的方法

        res = func()

        time_diff(t3, _format='M')

        return res

    def pretty_print_POST(self,req):
        """
        打印请求数据
        Returns:

        """
        print('{}\n{}\r\n{}\r\n\r\n{}'.format(
            '-----------START-----------',
            req.method + ' ' + req.url,
            '\r\n'.join('{}: {}'.format(k, v) for k, v in req.headers.items()),
            req.body,
        ))
    def myrequest(self,url,header,data):
        """

        Args:
            url:
            header:
            data:

        Returns:

        """
        req = requests.Request('POST', url, headers=header, data=data)
        prepped = req.prepare()

        # 在提交请求前，可以更改数据和参数
        # do something with prepped.body
        prepped.body = 'No, I want exactly this as the body.'

        # do something with prepped.headers
        del prepped.headers['Content-Type']


        self.pretty_print_POST(prepped)

        s = requests.Session()
        resp = s.send(prepped)
        print(resp.text)

        # resp = s.send(prepped,
        #               stream=stream,
        #               verify=verify,
        #               proxies=proxies,
        #               cert=cert,
        #               timeout=timeout
        #               )
        #
        # print(resp.status_code)


    def request(self, wrd=True):
        '''
        Post 请求
        :return:
        '''
        import traceback
        ssl._create_default_https_context = ssl._create_unverified_context

        # headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        headers = {'Content-Type': 'application/json'}

        dic = MyClass(self.host, self.p_raw, self.p_url)
        data = json.dumps(dic.raw, ensure_ascii=False, cls=NpEncoder)  #
        data = bytes(data, 'utf-8')

        print(dic.url + ' -- ')
        import datetime
        import time

        t3 = time.mktime(datetime.datetime.now().timetuple())  # **datetime转时间戳**
        # 这里调用你的方法

        # from requests.adapters import HTTPAdapter
        # from requests.packages.urllib3.poolmanager import PoolManager

        try:
            res = requests.post(dic.url, headers=headers, data=data, timeout=(60 * 60, 60 * 3), verify=False)
            reps = res.text

            # case 1 begin
            # # getHtmls(host + dic.url)
            # req = request.Request(dic.url, headers=headers, data=data)
            # res = request.urlopen(req).read()
            # reps = res.decode("utf-8")
            # # response = urlopen(request)
            # case 1 end

            time_diff(t3, _format='M')
            print(self.hum_convert(len(reps)))

            # t2 = datetime.datetime.now().microsecond
            # t4 = time.mktime(datetime.datetime.now().timetuple())
            #
            # strTime = 'funtion time use:%dms' % ((t4 - t3) * 1000 + (t2 - t1) / 1000)
            # print(strTime)
            # 是否对返回值进行解析

            if reps != '':
                if True:
                    data = json.loads(reps)

                    # import base64
                    # imgdata = base64.b64decode(data["data"]['data'])
                    # file = open('12.pdf', 'wb')
                    # file.write(imgdata)
                    # file.close()

                    # with open("\\1.pdf", "rb") as f:  # 转为二进制格式
                    #     base64_data = base64.b64encode(f.read())  # 使用base64进行加密
                    #     print(base64_data)
                    #     file = open('1.pdf', 'wt')  # 写成文本格式
                    #     file.write(base64_data)
                    #     file.close()

                    if wrd:
                        if data['data']['data'] == False:
                            print(reps)
                    reps = json.dumps(data, indent=2, ensure_ascii=False)  #

            print('state={}|{}'.format(res.status_code, reps))
            return res
        except Exception as e:
            # 打印异常信息
            print('error：' + str(e))
            print('str(Exception):\t', str(Exception))
            print('str(e):\t\t', str(e))
            print('repr(e):\t', repr(e))
            print('e.message:\t', e.message)
            print('traceback.print_exc():', traceback.print_exc())
            print('traceback.format_exc():\n%s' % traceback.format_exc())

    def request_get(self, enable_print=False):
        '''
        get请求，返回json 数据解析url 下载
        :return:
        '''

        url = self.host + self.p_url
        query = self.jsonDataToUrlParams(self.p_raw)
        print(url + ' -- ' + query)
        import datetime
        import time

        t3 = time.mktime(datetime.datetime.now().timetuple())  # **datetime转时间戳**
        # 这里调用你的方法

        # getHtmls(host + dic.url)
        res = requests.get(url=url, params=query, timeout=None)
        reps = res.text  # request.urlopen(rep).read().decode("utf-8")
        # response = urlopen(request)

        time_diff(t3, _format='M')
        print(self.hum_convert(len(res.text)))

        if enable_print and reps != '':
            data = json.loads(reps)
            if 'data' in data.keys() and data['data'] == False:
                print(reps)
            reps = json.dumps(data, indent=2, ensure_ascii=False)  #
            print_hi(reps)

        print_hi('state={}|{}'.format(res.status_code, reps))
        return res

    def req_get(self, _url, _query=None, _timeout=None):
        url = _url
        # if _raw != None:
        #     query = self.jsonDataToUrlParams(_raw)

        t3 = time.mktime(datetime.datetime.now().timetuple())  # **datetime转时间戳**
        # 这里调用你的方法

        # getHtmls(host + dic.url)
        res = requests.get(url=url, params=_query, timeout=_timeout)
        reps = res.text  # request.urlopen(rep).read().decode("utf-8")
        # response = urlopen(request)

        print(time_diff(t3, _format='M'))
        print(self.hum_convert(len(res.text)))

        print_hi('status_code={}'.format(res.status_code))
        return res

    def hum_convert(self, value):
        '''字节自适应转化单位KB、MB、GB'''
        units = ["B", "KB", "MB", "GB", "TB", "PB"]
        size = 1024.0
        for i in range(len(units)):
            if (value / size) < 1:
                return "%.2f%s" % (value, units[i])
            value = value / size

    def down_file(self, filename):
        '''
        直接文件下载==get请求
        :param filename:文件名
        :return:
        '''
        url = self.host + self.p_url

        print(url + ' -- ')
        fake_useragent = {
            'User-Agent': 'Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5355d Safari/8536.25',
            'Content-Type': 'application/json',
            'Accept-Encoding': 'gzip,deflate'
        }

        req = requests.get(url=url, headers=fake_useragent)  # stream=True,

        print(req.status_code)
        # 判断文件是否存在
        if req.status_code == 200:
            self.save_file(req, filename)
        pass

    def down_file_post(self, filename):
        '''
        直接文件下载==post请求，json参数
        :param filename:文件名
        :return:
        '''
        url = self.host + self.p_url

        print(url + ' -- ')
        fake_useragent = {
            'User-Agent': 'Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5355d Safari/8536.25',
            'Content-Type': 'application/json',
            'Accept-Encoding': 'gzip,deflate'
        }

        # post请求下载文件
        data = json.dumps(self.p_raw, ensure_ascii=False, cls=NpEncoder)  #
        data = bytes(data, 'utf-8')
        req = requests.post(url=url, data=data, headers=fake_useragent)

        # 判断文件是否存在
        self.save_file(req, filename)
        pass

    def down_file_post_path(self, filename):
        '''
        解析文件路径后，下载文件
        直接文件下载==post请求，json参数
        :param filename:文件名
        :return:
        '''
        url = self.host + self.p_url

        print(url + ' -- ')
        fake_useragent = {
            'User-Agent': 'Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5355d Safari/8536.25',
            'Content-Type': 'application/json',
            'Accept-Encoding': 'gzip,deflate'
        }

        # post请求下载文件
        data = json.dumps(self.p_raw, ensure_ascii=False, cls=NpEncoder)  #
        data = bytes(data, 'utf-8')

        t3 = time.mktime(datetime.datetime.now().timetuple())  # **datetime转时间戳**

        req = request.Request(url=url, data=data, headers=fake_useragent)
        reps = request.urlopen(req).read().decode("utf-8")

        if True:
            data = json.loads(reps)
            if False:
                if data['data']['data'] == False:
                    print(reps)
            else:
                if data['data'] != None:
                    # print(self.host + data['data'])
                    self.p_url = data['data']
                    self.down_file(filename)

            reps = json.dumps(reps.json(), indent=2, ensure_ascii=False)  #

        time_diff(t3, _format='M')
        print_hi(reps)

        # self.consume_time()

        pass

    def upload_file(self, file_path):
        ''' 上传文件'''
        url = self.host + self.p_url
        print(url)

        from urllib3 import encode_multipart_formdata
        # # from_data上传文件，注意参数名propertyMessageXml
        # data = MultipartEncoder(fields={'propertyMessageXml': ('filename', open('D:/123.xml', 'rb'), 'text/xml')})
        # requests.post(url=url, data=data, headers={'Content-Type': data.content_type})

        # # raw上传文件

        # file = open(file_path, 'rb')
        # res = requests.post(url=url, data=file, headers={'Content-Type': 'text/xml'})

        # binary上传文件
        # files = {'file': open(file_path, 'rb')}
        # requests.post(url=url, files=files, headers={'Content-Type': 'binary'})

        _p = os.path.dirname(os.getcwd()) + os.sep
        file_path = _p + file_path
        print(_p)

        files = {'file': open(file_path, 'rb')}  # , "image/jpeg"
        res = requests.post(url=url, files=files,
                            headers={'Content-Type': 'binary'})  # 'Content-Type': 'binary'
        print_hi(res.content.decode('utf-8'))

        return res

    def upload_file(self, path=None, file_path=None):
        ''' 亲测可用 file_path'''
        import requests, glob
        from urllib3 import encode_multipart_formdata

        url = self.host + self.p_url
        print(url)

        if path:
            for file_path in glob.glob(path + '\*'):  # 批量文件
                data = {}
                with open(file_path, 'rb') as file:
                    data['file'] = (file_path.split("/")[-1], file.read())  # 名称，读文件
                    file.close()
                encode_data = encode_multipart_formdata(data)
                res = requests.post(url, headers={'Content-Type': encode_data[1]}, data=encode_data[0])
                return res.text

        if file_path:
            data = {}
            _p = os.path.dirname(os.getcwd()) + os.sep
            file_path = _p + file_path
            print(_p)

            with open(file_path, 'rb') as file:
                data['file'] = (file_path.split("/")[-1], file.read())  # 名称，读文件
                file.close()
            encode_data = encode_multipart_formdata(data)
            res = requests.post(url, headers={'Content-Type': encode_data[1]}, data=encode_data[0])

            return res

    '''------------------------------ 以下功能函数 ------------------------------'''

    def jsonDataToUrlParams(self, params_data):
        ''' 将Json对象转化成Url字符串'''
        url_str = ''  # '?'
        nums = 0
        max_nums = len(params_data)
        for key in params_data:
            nums = nums + 1
            # 如果是最后一位就不要带上&
            # 拼为url字符串
            if nums == max_nums:
                url_str += str(key) + '=' + str(params_data[key])
            else:
                url_str += str(key) + '=' + str(params_data[key]) + '&'
        return url_str

    def save_file(self, res, filename):
        '''
        保存下载的文件
        '''

        if res.status_code != 200:
            print('http status_code ={}'.format(res.status_code))
            return
        # req.raise_for_status()  # 确保程序在下载失败时停止
        '''
        要求：调用时，判断 req.status_code == 200
        从Internet上下载文件和网页

        下载并保存到文件的步骤：
        ①调用requests.get()下载该文件
        ②用’wb’调用open()，以写二进制的方式打开一个新文件
        ③利用Respose对象的iter_content()方法循环
        ④在每次迭代中调用write()，将内容写入该文件
        ⑤调用close()关闭该文件
        ————————————————

        :param req:
        :param filename:
        :return:
        '''
        # 判断文件是否存在
        path = os.path.dirname(os.getcwd()) + os.sep + filename
        path = os.getcwd() + os.sep + filename

        abc = os.path.split(path)

        # 文件夹是否存在
        if not os.path.exists(abc[0]):
            os.makedirs(abc[0])

        # 如果文件已存在，则删除
        if os.path.exists(path) and os.path.isfile(path) == True:
            os.remove(path)

        with open(path, 'wb') as f:
            for chunk in res.iter_content(chunk_size=1024):
                f.write(chunk)

    def del_file(self, path_data):
        ''' 删除当前路径下的所有文件'''
        for i in os.listdir(path_data):  # os.listdir(path_data)#返回一个列表，里面是当前目录下面的所有东西的相对路径
            file_data = path_data + "\\" + i  # 当前文件夹的下面的所有东西的绝对路径
            if os.path.isfile(file_data) == True:  # os.path.isfile判断是否为文件,如果是文件,就删除.如果是文件夹.递归给del_file.
                os.remove(file_data)
            else:
                self.del_file(file_data)

    def save_base64file(self, content, filename):

        import base64
        # 判断文件是否存在
        path = os.path.dirname(os.getcwd()) + os.sep + filename
        path = os.getcwd() + os.sep + filename

        abc = os.path.split(path)

        # 文件夹是否存在
        if not os.path.exists(abc[0]):
            os.makedirs(abc[0])

        # 如果文件已存在，则删除
        if os.path.exists(path) and os.path.isfile(path) == True:
            os.remove(path)

        with open(path, 'wb') as f:
            base64_data = base64.b64decode(content)  # 使用base64进行加密
            f.write(base64_data)


if __name__ == '__main__':
    import requests

    url = "https://jzzhauth.lj996.cn/connect/token"

    payload = 'client_id=jzzh.mini&client_secret=vuYXqENhaXD86YFDB&grant_type=password&password=123456&username=13000000000'
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded'
    }

    # response = requests.request("POST", url, headers=headers, data=payload)
    response = requests.post(url, data=payload, headers=headers)

    print_hi(response.json())
    print(response.text)
